package com.banmao.mall.config;

import com.banmao.mall.realm.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 *  认证器，对Realm进行分发
 */
@Component
public class CustomAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();

        // 对realms进行分发
        MallToken token = (MallToken) authenticationToken;
        // 获取token的类型信息
        String type = token.getType();

        ArrayList<Realm> realms = new ArrayList<>();

        for (Realm originRealm : originRealms) {
            if(originRealm.getName().toLowerCase().contains(type)) {
                realms.add(originRealm);
            }
        }


        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
